/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.im.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.FlowUserAnalysis;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.im.bean.ImMsgBizUser;
import com.yami.shop.im.constants.SendType;
import com.yami.shop.im.service.ImMsgBizUserService;
import com.yami.shop.im.util.SecurityUtils;
import com.yami.shop.im.vo.Conversation;
import com.yami.shop.security.api.model.YamiUser;
import com.yami.shop.service.FlowUserAnalysisService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.sys.comment.model.SysUser;
import com.yami.shop.sys.comment.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * @author Lzk
 */
@RestController
@RequestMapping("/p/user")
@Api(tags = "用户聊天接口")
@AllArgsConstructor
public class UserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ShopDetailService shopDetailService;
    @Autowired
    private ImMsgBizUserService imMsgBizUserService;
    @Autowired
    private FlowUserAnalysisService flowUserAnalysisService;
    @Autowired
    private ProductService productService;

    @PostMapping("/conversations")
    @ApiOperation(value = "最后的对话信息列表项", notes = "获取最后的对话信息列表项")
    public ResponseEntity<Page<Conversation>> conversations(PageParam<ImMsgBizUser> pageParam) {
        YamiUser yamiUser = SecurityUtils.getUser();
        Page<ImMsgBizUser> imMsgBizUserPage = imMsgBizUserService.page(pageParam, new LambdaQueryWrapper<ImMsgBizUser>()
                .eq(ImMsgBizUser::getUserId, yamiUser.getUserId()).orderByDesc(ImMsgBizUser::getId));
        List<ImMsgBizUser> imMsgBizUsers = imMsgBizUserPage.getRecords();
        List<Conversation> conversations = new ArrayList<>();
        for (ImMsgBizUser imMsgBizUser : imMsgBizUsers) {
            Conversation conversation = new Conversation();
            conversation.setChatType(imMsgBizUser.getSendType());
            conversation.setShopId(imMsgBizUser.getBizId());
            conversation.setUserId(imMsgBizUser.getUserId());
            conversation.setLatestMsg(imMsgBizUser.getLastMsgContent());
            conversation.setUnread(imMsgBizUser.getUserUnreadNum());
            // todo 东8区，不应该写死"+8"后续优化
            conversation.setTimestamp(imMsgBizUser.getLastMsgTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            conversation.setTimeStr(DateUtil.format(Date.from(imMsgBizUser.getLastMsgTime().atZone(ZoneId.systemDefault()).toInstant()), "yyyy/MM/dd"));
            conversation.setLatestMsgTime(Date.from(imMsgBizUser.getLastMsgTime().atZone(ZoneId.systemDefault()).toInstant()));
            conversation.setType(imMsgBizUser.getLastMsgType());
            conversation.setEmployeeId(imMsgBizUser.getEmployeeId());
            if (Objects.equals(imMsgBizUser.getSendType(), SendType.PLATFORM)) {
                SysUser sysUser = sysUserService.getSysUserById(imMsgBizUser.getBizId());
                if (sysUser != null) {
                    conversation.setFriendName(sysUser.getNickName());
                }
            } else if (Objects.equals(imMsgBizUser.getSendType(), SendType.SHOP)) {
                ShopDetail shopDetail = shopDetailService.getShopDetailByShopId(imMsgBizUser.getBizId());
                if (shopDetail != null && shopDetail.getShopStatus() != null) {
                    conversation.setPic(shopDetail.getShopLogo());
                    conversation.setFriendName(shopDetail.getShopName());
                    conversation.setShopStatus(shopDetail.getShopStatus());
                }
            }
            conversations.add(conversation);
        }
        Page<Conversation> conversationPage = new Page<>();
        BeanUtils.copyProperties(imMsgBizUserPage, conversationPage);
        conversationPage.setRecords(conversations);
        return ResponseEntity.ok(conversationPage);
    }

    @PostMapping("/recentBrowse")
    @ApiOperation(value = "最近浏览的商品", notes = "获取最近浏览的商品")
    public ResponseEntity<List<Product>> recentBrowse(Long shopId, PageParam<FlowUserAnalysis> pageParam) {
        YamiUser yamiUser = SecurityUtils.getUser();
        Page<FlowUserAnalysis> flowUserAnalysisPage = flowUserAnalysisService.page(pageParam, new LambdaQueryWrapper<FlowUserAnalysis>()
                .eq(FlowUserAnalysis::getUserId, yamiUser.getUserId()).orderByDesc(FlowUserAnalysis::getFlowUserAnalysisId));
        Set<String> visitProdIdSet = new HashSet<>();
        for (FlowUserAnalysis flowUserAnalysis : flowUserAnalysisPage.getRecords()) {
            visitProdIdSet.addAll(Json.parseArray(flowUserAnalysis.getVisitProdIds(), String[].class));
        }
        if (CollectionUtil.isEmpty(visitProdIdSet)) {
            return ResponseEntity.ok(Collections.emptyList());
        }
        List<Product> productList = productService.list(new LambdaQueryWrapper<Product>().eq(Product::getShopId, shopId).in(Product::getProdId, visitProdIdSet));
        return ResponseEntity.ok(productList);
    }

}
